/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package warehouse;

import entity.CommodityLocal;
import entity.CommodityLocalHome;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import transfer.Commodity;

/**
 *
 * @author rebelizant
 */
public class PictureLoader extends HttpServlet {
    
    public static final String DATA_DIRECTORY = "images/commodity/";
    public static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
    public static final int MAX_REQUEST_SIZE = 1024 * 1024;
    
    public static final String ID_PARAMETER = "idCommodity";
    public static final String FILENAME_PARAMETER = "fileName";

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request); 
        if (!isMultipart) {
            return;
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(MAX_MEMORY_SIZE);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        String uploadFolder = getServletContext().getRealPath("")
                                    + File.separator + DATA_DIRECTORY;
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(MAX_REQUEST_SIZE);
        String fileName = null;
        String format = null;
        boolean flag = true;
        try {
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            Context c = new InitialContext();
            CommodityLocalHome commodityHome = (CommodityLocalHome) c.lookup("java:comp/env/Commodity");            
            CommodityLocal commodityLocal = null;
            Commodity commodity = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next(); 
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    if (ID_PARAMETER.equals(fieldName)) {
                        Integer id = new Integer(item.getString());
                        commodityLocal = commodityHome.findByPrimaryKey(id);
                        commodity = commodityLocal.getCommodity();
                        fileName = commodity.getCategory().getIdCategory()
                                + "_"
                                + commodity.getIdCommodity();
                    }
                    if (FILENAME_PARAMETER.equals(fieldName)) {
                        format = item.getString();
                    }
                } else {
                    if (item.getString().equals("")) {
                        flag = false;
                    }
                }
            }
            fileName += "." + format;
            iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField() && flag) {
                    commodity.setImage(fileName);
                    commodityLocal.setCommodity(commodity);
                    String filePath = uploadFolder + File.separator + fileName;
                    File uploadedFile = new File(filePath);
                    if (uploadedFile.exists()) {
                        uploadedFile.delete();
                        uploadedFile.createNewFile();
                    }
                    item.write(uploadedFile);
                }
            }
            response.setContentType("application/json;charset=UTF-8");            
        } catch (FileUploadException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            getServletContext().getRequestDispatcher("/admin/admin.jsp?content=product").forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
